import { DateObject } from '../types/common';
import { NameOfMonths } from '../types/month';
import { DateFormatInfo, UseNumber } from './types';

export function useNumber(): UseNumber {
    function getDayNumber(date: DateObject): number {
        return new Date(
            date.year || 0,
            (date.month || 1) - 1,
            date.day,
            date.hour ? date.hour : 0,
            date.minute ? date.minute : 0,
            date.second ? date.second : 0,
            0
        ).getDay();
    }

    function getNumberByValue(df: DateFormatInfo): number {
        if (!df) {
            return 1;
        }
        if (!/^\d+$/.test(df.value)) {
            return -1;
        }

        let nbr = Number(df.value);
        if (
            (df.format.length === 1 && df.value.length !== 1 && nbr < 10) ||
            (df.format.length === 1 && df.value.length !== 2 && nbr >= 10)
        ) {
            nbr = -1;
        } else if (df.format.length === 2 && df.value.length > 2) {
            nbr = -1;
        }
        return nbr;
    }

    function getMonthNumberByMonthName(df: DateFormatInfo, nameOfMonths: NameOfMonths): number {
        if (df.value) {
            for (let key = 1; key <= 12; key++) {
                if (df.value.toLowerCase() === nameOfMonths[key].toLowerCase()) {
                    return key;
                }
            }
        }
        return -1;
    }

    function getWeekNumber(date: DateObject): number {
        const d: Date = new Date(date.year || 0, (date.month || 1) - 1, date.day, 0, 0, 0, 0);
        d.setDate(d.getDate() + (d.getDay() === 0 ? -3 : 4 - d.getDay()));
        return Math.round((d.getTime() - new Date(d.getFullYear(), 0, 4).getTime()) / 86400000 / 7) + 1;
    }

    return { getNumberByValue, getDayNumber, getMonthNumberByMonthName, getWeekNumber };
}
